#include "kernel_operator.h"
#include "math.h"

constexpr int32_t TOTAL_LENGTH = 2048 * 4;
constexpr int32_t USE_CORE_NUM = 8;
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM;
constexpr int32_t TILE_NUM = 8;
constexpr int32_t BUFFER_NUM = 2;
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM;

using namespace AscendC;


template<typename TYPE_X, typename TYPE_Z,bool IsExistBigCore> 
class KernelSpectralMagnitude2D {
public:
    __aicore__ inline KernelSpectralMagnitude2D() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR z, uint64_t smallCoreDataNum,
                                uint64_t bigCoreDataNum, uint64_t bigCoreLoopNum, 
                                uint64_t smallCoreLoopNum, uint64_t ubPartDataNum, 
                                uint64_t smallCoreTailDataNum, uint64_t bigCoreTailDataNum, 
                                uint64_t tailBlockNum) 
    {
        ASSERT(AscendC::GetBlockNum() != 0 && "block dim can not be zero!");
        uint64_t coreNum = AscendC::GetBlockIdx();
        uint64_t globalBufferIndex = bigCoreDataNum * AscendC::GetBlockIdx();
        this->ubPartDataNum = ubPartDataNum;
        if constexpr (IsExistBigCore) 
        {
          if (coreNum < tailBlockNum) 
          { 
            this->coreDataNum = bigCoreDataNum;
            this->tileNum = bigCoreLoopNum;
            this->tailDataNum = bigCoreTailDataNum;
          }
          else 
          { 
            this->coreDataNum = smallCoreDataNum;
            this->tileNum = smallCoreLoopNum;
            this->tailDataNum = smallCoreTailDataNum;
            globalBufferIndex -= (bigCoreDataNum - smallCoreDataNum) * (AscendC::GetBlockIdx() - tailBlockNum);
          }
        }
        else
        {
          this->coreDataNum = smallCoreDataNum;
          this->tileNum = smallCoreLoopNum;
          this->tailDataNum = smallCoreTailDataNum;
          globalBufferIndex = smallCoreDataNum * AscendC::GetBlockIdx();
        }
          
        xGm.SetGlobalBuffer((__gm__ TYPE_X*)x + globalBufferIndex, this->coreDataNum);
        zGm.SetGlobalBuffer((__gm__ TYPE_Z*)z + globalBufferIndex, this->coreDataNum);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_Z));

        pipe.InitBuffer(abuf , this->ubPartDataNum * sizeof(float)*2);

        pipe.InitBuffer(indexbuf , this->ubPartDataNum * sizeof(uint32_t)*2);
        index = indexbuf.Get<uint32_t>(this->ubPartDataNum*2);

        /*
        AscendC::CreateVecIndex(index , (unsigned)0, this->ubPartDataNum);
        AscendC::CreateVecIndex(index[this->ubPartDataNum],  (unsigned)0, this->ubPartDataNum);
        AscendC::Muls(index, index, (uint32_t)8, this->ubPartDataNum); // 0,8,16,24,... + 0,8,16,24,...
        AscendC::Adds(index[this->ubPartDataNum], index[this->ubPartDataNum], (uint32_t)4, this->ubPartDataNum);

        As Cann does not supprt this API, we use SetValue to set index and revindex
      */
        //0,8,16,24,... real
        //4,12,20,28,... imag

        // 1) real,imag,real,imag ... -> real,real ...+  imag,imag ...
        //-> 0,8,16,24,...,4,12,20,28,...

        // 2) real,real ... + imag,imag ... -> real,imag,real,imag ...
    }
    
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->ubPartDataNum;

        if( loopCount-1 > 0)//save time for tail only case
          for(int i=0;i<this->processDataNum;i++){
            index.SetValue(i, i*8),
            index.SetValue(i+this->processDataNum, i*8+4);
          }

        for (int32_t i = 0; i < (loopCount-1); i++) 
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
        this->processDataNum = this->tailDataNum;

        for(int i=0;i<this->processDataNum;i++){
            index.SetValue(i, i*8),
            index.SetValue(i+this->processDataNum, i*8+4);
       }

        CopyIn(loopCount-1);
        Compute(loopCount-1);
        CopyOut(loopCount-1);
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.AllocTensor<TYPE_X>();
      AscendC::DataCopy(xLocal, xGm[progress * this->ubPartDataNum], this->processDataNum);
      inQueueX.EnQue(xLocal);
    }

    __aicore__ inline void Compute(int32_t progress)//sin(pi x)/(pi*x)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.DeQue<TYPE_X>();
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.AllocTensor<TYPE_Z>();
    
      AscendC::LocalTensor<float> a = abuf.Get<float>();

      auto xf=xLocal.template ReinterpretCast<float>();
      auto zf=zLocal.template ReinterpretCast<float>();


      AscendC::Gather(a, xf, index, (uint32_t)0, 2* this->processDataNum); 
      //a [x1 x1 ... y1 y1 ...]

      AscendC::Mul(xf, a, a, 2*this->processDataNum); 
      
      AscendC::Add(zf, xf, xf[this->processDataNum], this->processDataNum); // ad+bc

      AscendC::Sqrt(zf, zf, this->processDataNum); 

      outQueueZ.EnQue<TYPE_Z>(zLocal);
      inQueueX.FreeTensor(xLocal);
    }
    
    __aicore__ inline void CopyOut(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.DeQue<TYPE_Z>();  
      AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
      outQueueZ.FreeTensor(zLocal);
    }
private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueX;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> abuf, indexbuf;

    AscendC::LocalTensor<uint32_t> index;

    AscendC::GlobalTensor<TYPE_X> xGm;
    AscendC::GlobalTensor<TYPE_Z> zGm;
    uint64_t coreDataNum;
    uint64_t tileNum;
    uint64_t ubPartDataNum;
    uint64_t tailDataNum;
    uint64_t processDataNum;
};

//GM_ADDR input, GM_ADDR out, uint32_t size, uint32_t length,TPipe *PIPE)
  
extern "C" __global__ __aicore__ void spectral_magnitude2_d_custom(GM_ADDR input, GM_ADDR out)
{
    // GET_TILING_DATA(tiling_data, tiling);
    KernelSpectralMagnitude2D<uint64_t, float, 0 >op;
    op.Init(input, out, 
            TOTAL_LENGTH, TOTAL_LENGTH, 
            TOTAL_LENGTH/64, TOTAL_LENGTH/64, 
            64,
            64,64,33);


    /*
     op.Init(x, z, 
                tiling_data.smallCoreDataNum, tiling_data.bigCoreDataNum, 
                tiling_data.bigCoreLoopNum,   tiling_data.smallCoreLoopNum, 
                tiling_data.ubPartDataNum,    
                tiling_data.smallCoreTailDataNum, tiling_data.bigCoreTailDataNum,
                tiling_data.tailBlockNum);
    */
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void spectral_magnitude2_d_custom_do(uint32_t blockDim, void *stream, std::pair<float,float> *x, float *z)
{
    spectral_magnitude2_d_custom<<<blockDim, nullptr, stream>>>(x, z);
}
#endif
